import cv2  # 图像处理库OpenCV
import numpy as np  # 数值计算和数组处理库NumPy
from PIL import Image  # 图像处理库Pillow中的Image模块，用于创建图像对象
from PIL import ImageDraw  # 图像处理库Pillow中的ImageDraw模块，用于绘制图像

# 创建numpy数组，用于存储像素
img = np.zeros((1000, 1000, 3), np.uint8) + 255  # 创建一个1000x1000x3的三通道数组，初始值全为255表示白色背景
# 将numpy数组转为Image对象
pil_img = Image.fromarray(img)  # 将NumPy数组转换为PIL库中的Image对象
# 获取ImageDraw.Draw()对象
draw = ImageDraw.Draw(pil_img)  # 获取一个可以在Image对象上绘制的Draw对象

def L_Barsky(x0, y0, x1, y1):
    t = [0.0, 1.0]
    deltax = x1 - x0

    if not can_see(-deltax, x0 - xl, t):
        return False

    if not can_see(deltax, xr - x0, t):
        return False

    deltay = y1 - y0

    if not can_see(-deltay, y0 - yb, t):
        return False

    if not can_see(deltay, yt - y0, t):
        return False

    x1 = x0 + t[1] * deltax
    y1 = y0 + t[1] * deltay
    x0 = x0 + t[0] * deltax
    y0 = y0 + t[0] * deltay

    return True, x0, y0, x1, y1

def can_see(q, d, t):
    t0, t1 = t[0], t[1]
    if q < 0:
        r = d / q
        if r > t1:
            return False
        elif r > t0:
            t[0] = r
    elif q > 0:
        r = d / q
        if r < t0:
            return False
        elif r < t1:
            t[1] = r
    elif d < 0:
        return False
    return True




# 将Image对象转为numpy数组
img_array = np.array(pil_img)  # 调用np.array()方法将Image对象转换为NumPy数组
# 将numpy数组转为OpenCV图像
cv_img = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)  # 将NumPy数组转换为OpenCV图像

cv2.imshow("image", cv_img)  # 显示OpenCV图像窗口，窗口名称为"image"
cv2.waitKey(0)  # 等待鼠标事件，直到用户关闭显示窗口
cv2.destroyAllWindows()  # 销毁OpenCV窗口并关闭程序
